import {get} from "lodash";
import React from "react";
import Button from 'antd/lib/button';
import Select from 'antd/lib/select';
import Tree from 'antd/lib/tree';
import Modal from 'antd/lib/modal';
import 'antd/dist/antd.less'; 
import OrgStruct from "@/services/orgstruct";
import CreateOrgStructDialog from "@/components/orgstruct/OrgStructDialog";
import navigateTo from "@/components/ApplicationArea/navigateTo";
import OrgUnitTable from "@/components/orgstruct/OrgUnitTable";
import notification from "@/services/notification";
import {WarningOutlined,SecurityScanTwoTone,DownOutlined} from "@ant-design/icons";
const { confirm } = Modal;

export default class OrgStructTree extends React.Component {
  state = {
    orgstruct_id: 0,
    versions:[],
    loading: true,
    gData: [],
    isChanged: false,
  };

  componentWillMount() {
    this.loadData();
  }

  componentWillReceiveProps(nextProps){
    if (nextProps.orgstruct_enum !== this.props.orgstruct_enum) {
      this.setState({
        orgstruct_id: 0,
        versions:[],
        loading: true,
        gData: [],
        isChanged: false,
      }); 
      this.loadData(nextProps.orgstruct_enum);
    }
  }

  loadData(orgstruct_enum = this.props.orgstruct_enum) {
    OrgStruct.query(orgstruct_enum).then(data => {
      if (data && data.length >0)
        this.setState({
          versions: data,
          orgstruct_id: data[0].id,
          gData: data[0].details && [...data[0].details],
          loading: false,
        }); 
      else 
        this.setState({
          loading: false,
        });
    });
  }

  handleDelete = () => {
    confirm({
      title: '确定删除部门版本?',
      icon: <WarningOutlined />,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        OrgStruct.delete(this.state.orgstruct_id).then(() => {
          notification.success("部门版本删除成功.");
          this.loadData();
        }).catch(error => {
          notification.error(get(error, "response.data.message", "删除失败."));
        });
      },
    });
  };

  onDragEnter = info => {
    window.console.log(info);
  };

  onDrop = info => {
    window.console.log(info);
    const dropKey = info.node.props.eventKey;
    const dragKey = info.dragNode.props.eventKey;
    const dropPos = info.node.props.pos.split('-');
    const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);

    const loop = (data, key, callback) => {
      data.forEach((item, index, arr) => {
        if (item.key === key) {
          return callback(item, index, arr);
        }
        if (item.children) {
          return loop(item.children, key, callback);
        }
      });
    };
    const data = [...this.state.gData];

    // Find dragObject
    let dragObj;
    loop(data, dragKey, (item, index, arr) => {
      arr.splice(index, 1);
      dragObj = item;
    });

    if (!info.dropToGap) {
      // Drop on the content
      loop(data, dropKey, item => {
        item.children = item.children || [];
        // where to insert 示例添加到尾部，可以是随意位置
        item.children.push(dragObj);
      });
    } else if (
      (info.node.props.children || []).length > 0 && // Has children
      info.node.props.expanded && // Is expanded
      dropPosition === 1 // On the bottom gap
    ) {
      loop(data, dropKey, item => {
        item.children = item.children || [];
        // where to insert 示例添加到头部，可以是随意位置
        item.children.unshift(dragObj);
      });
    } else {
      let ar;
      let i;
      loop(data, dropKey, (item, index, arr) => {
        ar = arr;
        i = index;
      });
      if (dropPosition === -1) {
        ar.splice(i, 0, dragObj);
      } else {
        ar.splice(i + 1, 0, dragObj);
      }
    }

    this.setState({
      gData: data,
      isChanged: true,      
    });
  };

  selectChange = (value = 0) => {

    if (value === 0){
       value = this.state.orgstruct_id;
    }
      OrgStruct.get(value).then(data => {
        this.setState({
          gData: data.details,
          orgstruct_id: value,
          loading: false,
        });
      })
      .catch(error => {
        notification.error(error.message, error.detailedMessage);
      });
  };

  handleSave = () =>{
    const loop = (das, index) => {
      let items=[];
      das.forEach((item) => {
        item.icon= "";
        if (item.children) {
          item.children= loop(item.children, index+1);
        }
        items.push(item);
      });
      return items;
    };
    let datas=loop(this.state.gData,0);
    OrgStruct.save(this.state.orgstruct_id,datas).then(() => {
      notification.success("部门保存成功。");
      this.setState({
        isChanged: false,
      });
    });
}

  showCreateOrgVersionDialog = () => {
    CreateOrgStructDialog.showModal({orgstruct_enum: this.props.orgstruct_enum})
      .onClose((result = {}) => {
        if (result.success) {
          this.loadData();
        }
      }).onDismiss(() => {
        navigateTo("orgstruct", true);
      });
  };

  renderSelect() {
    if (this.state.orgstruct_id === 0) 
    return (<Select style={{ width: 200 }} onChange={this.selectChange} />);
else
      return (
          <Select style={{ width: 200 }} defaultValue={this.state.orgstruct_id} onChange={this.selectChange}>
            {this.state.versions.map(item => (
                <option value={item.id}>{item.effect_date} 至 {item.expire_date && item.expire_date}</option>
            ))}
          </Select>
      );
  };

  render() {
    if (this.state.loading) return null;
    const loop = (das, index) => {
      let items=[];
      das.forEach((item) => {
        item.icon= <SecurityScanTwoTone />;
        if (item.children) {
          item.children= loop(item.children, index+1);
        }
        items.push(item);
      });
      return items;
    };
    let datas=loop(this.state.gData,0);
    return(
      <div className="row">
        <div className="col-sm-6">
         <Button type="primary" onClick={this.handleSave} disabled={!this.state.isChanged}>
            <i className="fa fa-save m-r-5" />
            保存
          </Button>
          <label>版本有效期：
          {this.renderSelect()}</label>
          <Button type="primary" onClick={this.showCreateOrgVersionDialog}>
            <i className="fa fa-plus m-r-5" />
            新版本
          </Button>
          <Button type="primary" onClick={this.handleDelete} disabled={!this.state.orgstruct_id}>
            <i className="fa fa-remove m-r-5"/>
            删除版本
          </Button>
          <Tree
            className="draggable-tree"
            draggable
            blockNode
            showIcon
            // showLine
            switcherIcon={<DownOutlined />}
            defaultExpandAll
            onDragEnter={this.onDragEnter}
            onDrop={this.onDrop}
            treeData={datas}
          />
        </div>
        <div className="col-sm-6">
          <OrgUnitTable orgstruct_id={this.state.orgstruct_id} selectChange={this.selectChange} />
        </div>
      </div>
    );
  }
}
